package cn.wjx.taobaounion.ui.custom;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

import cn.wjx.taobaounion.R;
import cn.wjx.taobaounion.utils.LogUtils;

/**
 * @author WuChangJian
 * @date 2020/6/25 7:49
 */
public class LoadingView extends AppCompatImageView {

    private float mDegrees = 0;
    private boolean mNeedRotate;
    public LoadingView(Context context) {
        this(context, null);
    }

    public LoadingView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setImageResource(R.mipmap.loading);
    }

    @Override
    protected void onAttachedToWindow() {
        // LogUtils.d(this, "onAttachedToWindow...");
        super.onAttachedToWindow();
        mNeedRotate = true;
        startRotate();
    }

    private void startRotate() {
        post(new Runnable() {
            @Override
            public void run() {
                mDegrees += 10;
                if (mDegrees >= 360) {
                    mDegrees = 0;
                }
                invalidate();
                if (!mNeedRotate || getVisibility() != VISIBLE) {
                    removeCallbacks(this);
                } else {
                    postDelayed(this, 10);
                }
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        LogUtils.d(this, "onDetachedFromWindow...");
        stopRotate();
        super.onDetachedFromWindow();
    }

    private void stopRotate() {
        mNeedRotate = false;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.rotate(mDegrees, getWidth() / 2f, getHeight() / 2f);
        super.onDraw(canvas);
    }
}
